// pages/order/order.js
const app = getApp()
import {
  orderList,
  orderCounts,
  orderReceiveConfirm,
  orderCancel,
  orderPaySign,
  orderPay,
  deleteOrders
} from '../../api/url.js'
import { formatOrderPayTime, getRandomNum} from '../../utils/util.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showModal: false, //是否显示登录授权模态框
    currentState: '17', //现在订单类型
    orderCounts: null, //各订单数量
    list: [],//订单列表
    cancelItem:null,//取消订单项
    page:1,//请求页码
    size:20,//请求数据量
    loadOver:false,//是否请求完所有数据
    promptHeight: wx.getSystemInfoSync().windowHeight + 'px',
    cancelReason: [
      '我不想买了',
      '信息填写错误，重新拍',
      '卖家缺货',
      '其他原因',
    ],
    selectedReason: '我不想买了',
  },
  /**
   * @method
   * @desc 切换tab
   */
  changeState(e){
    let that=this
    that.setData({
      currentState:e.currentTarget.dataset.state,
      page:1,
      loadOver:false,
      list:[]
    })
    that.loadOrders(that.data.currentState)
  },
  /**
   * @method
   * @desc 确认收货
   */
  confirmGetGoods: function (e) {
    const that = this
    wx.showModal({
      title: '请收到宝贝后再确认收货',
      confirmColor: '#f8d683',
      success: function (res) {
        if (res.confirm) {
          const orderId = e.currentTarget.dataset.item.fId
          wx.showLoading({
            title: '确认收货中',
            mask:true
          })
          wx.request({
            url: orderReceiveConfirm,
            data:{
              fId: orderId,
              loginName: app.globalData.userInfo.loginname,
              token: wx.getStorageSync('token'),
              fUserId: app.globalData.userInfo.id,
            },
            success(res){
              wx.hideLoading()
              if(res.data.code===0){
                let temOrders = that.data.list
                temOrders.forEach(val=>{
                  if (val.fId===orderId){
                    val.fState=3
                  }
                })
                that.setData({
                  list:temOrders
                })
                that.loadOrderCounts()
              }else{
                wx.showToast({
                  title: '确认收货异常',
                  icon:'none'
                })
              }
            },
            fail(){
              wx.hideLoading()
              wx.showToast({
                title: '确认收货失败',
                icon:'none'
              })
            }
          })
        }
      }
    })
  },
  /**
   * @method
   * @desc 跳转物流
   */
  goLogistics(e){
    wx.navigateTo({
      url: '/pages/logistics/logistics?id='+e.currentTarget.dataset.item.fId,
    })
  },
  /**
   * 去付款
   */
  tapPayOrder(e) {
    console.log('打印e')
    console.log(e)
    let that = this
    const orderId = e.currentTarget.dataset.item.fId//orderId
    let list = that.data.list

    const order = list.find(i => i.fId === orderId)
    if (!order) return

    let desc = ''
    if (order.list && order.list.length) {
      desc += order.list.map(i => `${i.fProductName}x${i.fCount}`).join(';')
    }
    const orderNo = order.fOrderId
    const toPay = order.fOrderAmount
    const time = formatOrderPayTime(Date.now())
    const random = getRandomNum(6)
    const amount = toPay.toFixed(2)
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        const jsCode = res.code
        wx.showLoading({
          title: '加载中',
          mask: true
        })
        wx.request({
          url: orderPaySign,
          data: {
            time,
            randomKey: random,
            orderNo: orderId,
            loginName: app.globalData.userInfo.loginname,
            token: wx.getStorageSync('token'),
            userId: app.globalData.userInfo.id,
            fUserId: app.globalData.userInfo.id
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: 'POST',
          success(res) {
            if (res.data.code === 0) {//获取支付签名成功
              const digest = res.data.msg
              var userId = app.globalData.userInfo.id
              var loginName = app.globalData.userInfo.loginname
              wx.request({
                url: orderPay,
                method: 'POST',
                header: {
                  'content-type': 'application/json',
                  userId,
                  Time: time,
                  Authentication: `${loginName}:${random}:${amount}:${digest}`,
                },
                data: {
                  orderID: orderId,
                  orderCode: orderNo,
                  payCode: orderNo,
                  description: JSON.stringify('购买' + desc),
                  appId: 'wxf34e48c761b604a2',
                  appSecret: 'debe1169aaa6545cf433aaad69c107da',
                  jsCode: jsCode,
                  onLineStyle: 'wechat',
                  browseType: 'app',
                  toPay: amount,
                  sellerCode: '2088801555885173',
                  sellerName: JSON.stringify(desc),
                  requestBiz: '001',
                  createTime: Date.now(),
                  invalidTime: 6000,
                  loginName: app.globalData.userInfo.loginname,
                  token: wx.getStorageSync('token'),
                  userId: app.globalData.userInfo.id,
                  fUserId: app.globalData.userInfo.id
                },
                success(res) {
                  console.log(res)
                  if (res.data.errorCode === '0') {
                    //得到支付参数付款
                    console.log('打印支付参数')
                    console.log(res)
                    const data = JSON.parse(res.data.data.payData)
                    console.log(data)
                    wx.requestPayment({
                      'timeStamp': data.timeStamp,
                      'nonceStr': data.nonceStr,
                      'package': data.package,
                      'signType': 'MD5',
                      'paySign': data.sign,
                      'success': function (res) {
                        if (res.errMsg === 'requestPayment:ok') {
                          wx.hideLoading()
                          wx.showToast({
                            title: '支付成功',
                            icon: 'none'
                          })
                          let temList=that.data.list
                          temList.forEach(val=>{
                            // return val.fId!=orderId
                            if (val.fId == orderId){
                              val.fState=1
                            }
                          })
                          that.setData({
                            list:temList
                          })
                        } else {
                          wx.showToast({
                            title: '支付失败',
                            icon: 'none'
                          })
                        }
                      },
                      'fail': function (err) {
                        wx.hideLoading()
                        wx.showToast({
                          icon: 'none',
                          title: err.msg || '订单支付失败',
                        })
                      }
                    })
                  } else {
                    wx.showToast({
                      title: '获取支付参数异常',
                    })
                  }
                },
                fail() {
                  wx.showToast({
                    title: '获取支付参数失败',
                  })
                }
              })
            } else {
              wx.showToast({
                title: '获取支付签名异常',
              })
            }
          },
          fail() {
            wx.showToast({
              title: '获取支付签名失败',
              icon: 'none'
            })
          }
        })
      },
      fail: res => {
        wx.showToast({
          icon: 'none',
          title: '微信认证失败',
        })
      }
    })
  },
  /**
   * @method
   * @desc 根据订单状态做相应操作
   */
  doOrderOperation(e){
    let that=this
    let item=e.currentTarget.dataset.item
    switch (item.fState){
      case 0:
        //去付款
        that.tapPayOrder(e)
        break
      case 1:
        //催促发货
        wx.showToast({
          title: '已催促商家尽快发货~',
          icon:'none'
        })
        break
      case 2:
        //确认收货
        that.confirmGetGoods(e)
        break
      case 3:
        //去评价
        wx.navigateTo({
          url: '/pages/orderComment/orderComment?id=' + item.fId,
        })
        break
      case 4:
        //再来一单
        wx.navigateTo({
          url: '/pages/goodsDetail/goodsDetail?id=' + item.list[0].fProductId,
        })
        break
      case 5:
        //再来一单
        wx.showModal({
          title: '温馨提醒',
          content: '您确定要删除订单吗？',
          success(res){
            if(res.confirm){
              wx.request({
                url: deleteOrders,
                data: {
                  fId: item.fId,
                  loginName: app.globalData.userInfo.loginname,
                  token: wx.getStorageSync('token'),
                  fUserId: app.globalData.userInfo.id
                },
                success(res) {
                  if (res.data.code === 0) {
                    wx.showToast({
                      title: '删除订单成功',
                      icon: 'none'
                    })
                    let temList = that.data.list
                    temList.forEach((val, idx, arr) => {
                      if (val.fId === item.fId) {
                        arr.splice(idx, 1)
                      }
                    })
                    that.setData({
                      list: temList
                    })
                    that.loadOrderCounts()
                  } else {
                    wx.showToast({
                      title: '删除订单异常',
                      icon:'none'
                    })
                  }
                },
                fail(){
                  wx.showToast({
                    title: '删除订单失败',
                    icon:'none'
                  })
                }
              })
            }
          }
        })
        
        break
      case -1:
        //查看进程
        break
    }
  },
  /**
   * @method
   * 授权回调
   */
  settingCB(res) {
    let that = this
    if (res.detail.detail.errMsg === 'getUserInfo:ok') {
      app.globalData.wxUserInfo = res.detail.detail.userInfo
      wx.showLoading({
        title: '用户登录',
        mask: true
      })
      app.getUserInfo().then(res => {
        wx.hideLoading()
        that.setData({
          showModal: false
        })
        if (res.data.code === 0) {
          //做其它操作
          app.loadCollections(0, 9999, app.globalData.userInfo.loginname)
        } else {
          wx.showToast({
            title: '用户登录失败',
            icon: 'none'
          })
        }
      })
    } else {
      that.setData({
        showModal: false
      })
    }
  },
  /**
   * @method
   * @desc 关闭模态框
   */
  closeModal() {
    let that = this
    that.setData({
      showModal: false
    })
  },
  /**
   * @method 
   * @desc 处理加载订单请求结果
   * @param res 响应结果
   */
  doResponse(res){
    let that=this
    if (res.data.code === 0) {
      let temList = res.data.response.cont.list
      if(temList.length<that.data.size){//加载完订单
        that.setData({
          loadOver:true,
          page:that.data.page+1
        })
      }else{//未加载完订单
        that.setData({
          loadOver: false,
          page: that.data.page + 1
        })
      }
      temList.forEach(val => {
        val.totalPri = 0
        val.list.forEach(val1 => {
          val1.img = app.globalData.imageBaseUrl + val1.productImage.fThumbImage
          if (val1.productSku.skuPropertyValueList.length > 0) {
            val1.skuTxt = val1.productSku.skuPropertyValueList.map(val2 => (val2.propertyName + ':' + val2.fName)).join(';')
          }
          val1.priTxt = val1.fPrice.toFixed(2)
          // val.totalPri += val1.fPrice
        })
        val.totalPriTxt = val.fOrderAmount.toFixed(2)
      })
      that.setData({
        list: that.data.list.concat(temList)
      })
    } else {
      wx.showToast({
        title: '加载订单异常',
        icon: 'none'
      })
    }
  },
  /**
   * @method
   * @desc 加载订单
   */
  loadOrders(orderType) {
    let that = this
    if(!that.data.loadOver){
      let queryParam
      if (orderType == '17') {
        queryParam = {
          page: that.data.page,
          size: that.data.size,
          loginName: app.globalData.userInfo.loginname,
          token: wx.getStorageSync('token'),
          fUserId: app.globalData.userInfo.id
        }
      } else {
        queryParam = {
          page: that.data.page,
          size: that.data.size,
          loginName: app.globalData.userInfo.loginname,
          token: wx.getStorageSync('token'),
          fUserId: app.globalData.userInfo.id,
          fState: orderType
        }
      }
      wx.showLoading({
        title: '加载中',
        mask:true
      })
      wx.request({
        url: orderList,
        data: queryParam,
        success(res) {
          wx.hideLoading()
          that.doResponse(res)
        },
        fail() {
          wx.hideLoading()
          wx.showToast({
            title: '加载订单失败',
            icon: 'none'
          })
        }
      })
    }else{
      wx.showToast({
        title: '已加载完订单',
        icon:'none'
      })
    }
  },

  //点击订单跳转订单详情
  goOrderDetail: function(e) {
    wx.navigateTo({
      url: '../orderDetail/orderDetail?id=' + e.currentTarget.dataset.item.fId
    })
  },
  //点击取消订单
  cancelOrder: function(e) {
    var self = this
    wx.showModal({
      title: '提示',
      content: '确定取消此订单',
      success: function(res) {
        if (res.confirm) {
          self.setData({
            isShowDomal: true,
            cancelItem:e.currentTarget.dataset.item
          })
        }
      }
    })
  },
  //隐藏取消订单modal
  hideModal: function(e) {
    this.setData({
      isShowDomal: false
    })
  },
  //选择取消订单的原因
  tapSelectReason(e) {
    this.setData({
      selectedReason: e.currentTarget.dataset.reason
    })
  },
  //点击取消时隐藏取消订单原因modal
  onCancel: function() {
    this.hideModal()
  },
  //选择取消订单原因之后点击确定
  onConfirm: function() {
    let that=this
    this.hideModal()
    wx.request({
      url: orderCancel,
      data:{
        fId:that.data.cancelItem.fId,
        loginName: app.globalData.userInfo.loginname,
        token: wx.getStorageSync('token'),
        fUserId: app.globalData.userInfo.id
      },
      success(res){
        if(res.data.code===0){
          let temOrders = that.data.list
          temOrders.forEach(val => {
            if (val.fId === that.data.cancelItem.fId) {
              val.fState = 5
            }
          })
          that.setData({
            list:temOrders
          })
          that.loadOrderCounts()
        }else{
          wx.showToast({
            title: '取消订单异常',
            icon:'none'
          })
        }
      },
      fail(){
        wx.showToast({
          title: '取消订单失败',
          icon:'none'
        })
      }
    })
  },
  /**
   * @method
   * @desc 加载订单数量
   */
  loadOrderCounts() {
    let that = this
    wx.request({
      url: orderCounts,
      data: {
        loginName: app.globalData.userInfo.loginname,
        token: wx.getStorageSync('token'),
        fUserId: app.globalData.userInfo.id
      },
      success(res) {
        if (res.data.code === 0) {
          let temObj = res.data.response.cont
          that.setData({
            orderCounts: temObj
          })
        }else{
          wx.showToast({
            title: '加载订单数量异常',
            icon:'none'
          })
        }
      },
      fail(){
        wx.showToast({
          title: '加载订单数量失败',
          icon:'none'
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this
    if(options.type){
      that.setData({
        currentState:options.type
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let that = this
    app.userLogin().then(res => {
      wx.hideLoading()
      if (res === 'noAuthorize') {
        that.setData({
          showModal: true
        })
      } else if (res === 'success') {
        that.setData({
          showModal: false
        })
        //做其它请求
        that.loadOrders(that.data.currentState)
        that.loadOrderCounts()
      } else if (res === 'fail') {
        that.setData({
          showModal: false
        })
        wx.showToast({
          title: '注册用户失败',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    let that=this
    that.setData({
      showModal: false, //是否显示登录授权模态框
      currentState: '17', //现在订单类型
      orderCounts: null, //各订单数量
      list: [],//订单列表
      cancelItem: null,//取消订单项
      page: 1,//请求页码
      loadOver: false,//是否请求完所有数据
    })
    that.loadOrders(that.data.currentState)
    that.loadOrderCounts()
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    let that=this
    that.loadOrders(that.data.currentState)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})